package com.usian.service.impl;

import com.usian.JsonUtils;
import com.usian.mapper.*;
import com.usian.mq.MQSender;
import com.usian.pojo.*;
import com.usian.redis.RedisClient;
import com.usian.service.OrderService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;

    @Autowired
    private TbOrderShippingMapper tbOrderShippingMapper;

    @Autowired
    private TbItemMapper tbItemMapper;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private LocalMessageMapper localMessageMapper;

    @Autowired
    private MQSender mqSender;

    @Value("${ORDER_ID_KEY}")
    private String ORDER_ID_KEY;

    @Value("${ORDER_ID_BEGIN}")
    private Long ORDER_ID_BEGIN;

    @Value("${ORDER_ITEM_ID_KEY}")
    private String ORDER_ITEM_ID_KEY;

    @Override
    public Long insertOrder(OrderInfo orderInfo) {
//        tborder
        long timeMillis = System.currentTimeMillis();
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+timeMillis);
        Date date = new Date();
//        生成TbOrder主键id
        if (!redisClient.exists(ORDER_ID_KEY)) {
            redisClient.set(ORDER_ID_KEY,ORDER_ID_BEGIN);
        }
        Long orderId = redisClient.incr(ORDER_ID_KEY, 5L);
        TbOrder tbOrder = orderInfo.getTbOrder();
        tbOrder.setOrderId(orderId.toString());
        tbOrder.setCreateTime(date);
        tbOrder.setUpdateTime(date);
        tbOrder.setStatus(1);
        int num = tbOrderMapper.insertSelective(tbOrder);
//        tborder_item
//        生成TbOrder_Item主键Id
        if (!redisClient.exists(ORDER_ITEM_ID_KEY)) {
            redisClient.set(ORDER_ITEM_ID_KEY,ORDER_ID_BEGIN);
        }
        Long orderItemId = redisClient.incr(ORDER_ITEM_ID_KEY, 5L);
        String orderItem = orderInfo.getOrderItem();
        List<TbOrderItem> orderItemList = JsonUtils.jsonToList(orderItem, TbOrderItem.class);
        for (TbOrderItem tbOrderItem : orderItemList) {
            tbOrderItem.setId(orderItemId.toString());
            tbOrderItem.setOrderId(orderId.toString());
            int num1 = tbOrderItemMapper.insertSelective(tbOrderItem);
        }

//        tborder_shipping
        TbOrderShipping tbOrderShipping = orderInfo.getTbOrderShipping();
        tbOrderShipping.setOrderId(orderId.toString());
        tbOrderShipping.setCreated(date);
        tbOrderShipping.setUpdated(date);
        int num2 = tbOrderShippingMapper.insertSelective(tbOrderShipping);
//        分布式事务记录本地消息记录表
        LocalMessage localMessage = new LocalMessage();
        localMessage.setTxNo(UUID.randomUUID().toString());
        localMessage.setOrderNo(orderId.toString());
        localMessage.setState(0);//0代表失败的，1代表成功的
        localMessageMapper.insertSelective(localMessage);
//        发布消息到mq，完成扣减库存
//        amqpTemplate.convertAndSend("order_exchange", "order.add", orderId);
        mqSender.sendMsg(localMessage);
        return orderId;
    }

    /**
     * 关闭超时订单
     *
     * @return
     */
    @Override
    public List<TbOrder> selectOvertimeOrder() {
        List<TbOrder> tbOrders = tbOrderMapper.selectOvertimeOrder();
        return tbOrders;
    }

    /**
     * 关闭超时订单
     *
     * @param tbOrder
     */
    @Override
    public void updateOverTimeTbOrder(TbOrder tbOrder) {
        tbOrder.setStatus(6);
        Date date = new Date();
        tbOrder.setEndTime(date);
        tbOrder.setUpdateTime(date);
        tbOrder.setCloseTime(date);
        tbOrderMapper.updateByPrimaryKey(tbOrder);
    }

    /**
     * 将超时订单中的商品库存数量加回去
     *
     * @param orderId
     */
    @Override
    public void updateTbItemByOrderId(String orderId) {
//        通过orderId查询超时订单
        TbOrderItemExample tbOrderItemExample = new TbOrderItemExample();
        TbOrderItemExample.Criteria criteria = tbOrderItemExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<TbOrderItem> tbOrderItems = tbOrderItemMapper.selectByExample(tbOrderItemExample);
//        修改商品库存
        for (TbOrderItem tbOrderItem : tbOrderItems) {
            TbItem tbItem = tbItemMapper.selectByPrimaryKey(Long.valueOf(tbOrderItem.getItemId()));
            tbItem.setNum(tbItem.getNum()+tbOrderItem.getNum());
            tbItem.setUpdated(new Date());
            tbItemMapper.updateByPrimaryKey(tbItem);
        }
    }
}
